package cn.fbs.util;


import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;
import java.util.Iterator;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;

import cn.fbs.util.imageshort.FileUtil;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.text.PDFTextStripper;

/**
 * @program: BQ
 * @description: pdf工具类
 * @author: 张丽婧
 * @create: 2020-12-31 10:31
 **/

public class PdfUtil {
  //private static Logger logger = (Logger) LoggerFactory.getLogger(PdfUtil.class);

  /**
   * 通过PDFbox获取文章总页数
   *
   * @param filePath:文件路径
   * @return
   * @throws IOException
   */
  public static int getNumberOfPages(String filePath) throws IOException {
    PDDocument pdDocument = PDDocument.load(new File(filePath));
    int pages = pdDocument.getNumberOfPages();
    pdDocument.close();
    return pages;
  }

  /**
   * 通过PDFbox获取文章内容
   *
   * @param filePath
   * @return
   */
  public static String getContent(String filePath) throws IOException {
    PDFParser pdfParser = new PDFParser(
        new org.apache.pdfbox.io.RandomAccessFile(new File(filePath), "rw"));
    pdfParser.parse();
    PDDocument pdDocument = pdfParser.getPDDocument();
    String text = new PDFTextStripper().getText(pdDocument);
    pdDocument.close();
    return text;
  }

  /**
   * 通过PDFbox生成文件的缩略图
   *
   * @param filePath：文件路径
   * @param outPath：输出图片路径
   * @throws IOException
   */
  public static String getThumbnails(String filePath, String outPath,int compressRatio) throws IOException {
    // 利用PdfBox生成图像
    PDDocument pdDocument = PDDocument.load(new File(filePath));
    PDFRenderer renderer = new PDFRenderer(pdDocument);

    // 构造图片
    BufferedImage imgTemp = renderer.renderImageWithDPI(0, 30, ImageType.RGB);

    // 设置图片格式
    Iterator<ImageWriter> it = ImageIO.getImageWritersBySuffix("png");
    // 将文件写出
    ImageWriter writer = it.next();
    FileOutputStream fileOutputStream = new FileOutputStream(outPath);
    ImageOutputStream imageout = ImageIO.createImageOutputStream(fileOutputStream);

    writer.setOutput(imageout);
    writer.write(new IIOImage(imgTemp, null, null));
    imgTemp.flush();
    imageout.flush();
    imageout.close();
    fileOutputStream.close();
    pdDocument.close();
//    FileInputStream fileInputStream = new FileInputStream(new File(outPath));
//    int available = fileInputStream.available();
//    byte[] bytes = new byte[available];
//    fileInputStream.read(bytes);
    String base64 = FileUtil.getCompressBase64FromUrl(new File(outPath), compressRatio);
    return base64;
  }

  /**
   * PDF转图片 根据页码一页一页转
   *
   * @throws IOException imgType:转换后的图片类型 jpg,png
   */
  public static String PDFToImg(String fileUrl, int page, String imgType)
      throws IOException {
    PDDocument pdDocument = null;
    String base64 = null;
    /* dpi越大转换后越清晰，相对转换速度越慢 */
    int dpi = 50;
    try {
      pdDocument = getPDDocument(fileUrl);
      PDFRenderer renderer = new PDFRenderer(pdDocument);
      int pages = pdDocument.getNumberOfPages();
      //输出流
      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      if (page <= pages && page >= 0) {
        BufferedImage image = renderer.renderImageWithDPI(page, dpi);
        ImageIO.write(image, imgType, stream);
        base64 = Base64.getEncoder().encodeToString(stream.toByteArray()).replaceAll("\\n", "");
        //System.out.println("data:image/png;base64,"+base64);
      }

    } finally {
      if (pdDocument != null) {
        pdDocument.close();
      }
    }
    return "data:image/png;base64," + base64;
  }

  private static PDDocument getPDDocument(String fileUrl) throws IOException {
    File file = new File(fileUrl);
    FileInputStream inputStream = new FileInputStream(file);
    return PDDocument.load(inputStream);
  }


  public static void main(String[] args) throws IOException {
   /* String filePath = "C:\\Users\\16417\\Desktop\\BQ项目相关内容\\QB展示子系统工作计划一览表.pdf";
    int numberOfPages = PdfUtil.getNumberOfPages(filePath);
    System.out.println("该pdf总页数为：" + numberOfPages);
    System.out.println(
        "内容" + PdfUtil.getContent("C:\\Users\\16417\\Desktop\\BQ项目相关内容\\QB展示子系统工作计划一览表.pdf"));*/
    //获取pdf的前三页图片(若不足三页,有几页获取几页)

    System.out.println(PdfUtil.PDFToImg("E:/minio/miniocc/copy/2——2585482210281216730.pdf",
        0, "PNG"));


  }


  public static String getBase64(String path) {
    File file = new File(path);
    String base64 = null;
    try {
      BufferedImage image = ImageIO.read(file);
      Integer width = image.getWidth();
      Integer height = image.getHeight();
      System.out.println("宽：" + width + " 高:" + height);

      //输出流
      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      ImageIO.write(image, "png", stream);
      base64 =Base64.getEncoder().encodeToString(stream.toByteArray());
      System.out.println(base64);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return base64;

  }
}